# Function: test chat2grid.py
from chart_to_grid import *
import tkinter as tk
from PIL import Image, ImageTk
from grid_make import GridFiller


def display_image_with_scrollbars(image):
    class ImageZoomer:
        def __init__(self, original_image):
            self.original_image = original_image
            self.current_scale = 1.0

        def zoom(self, event):
            scale_factor = 1.1
            if event.delta > 0:
                self.current_scale *= scale_factor  # Zoom in
            else:
                self.current_scale /= scale_factor  # Zoom out

            # Resizing the image
            width, height = self.original_image.size
            new_size = int(self.current_scale * width), int(self.current_scale * height)
            resized_image = self.original_image.resize(new_size, Image.Resampling.LANCZOS)

            # Update the image on the canvas
            global tk_image
            tk_image = ImageTk.PhotoImage(resized_image)
            canvas.create_image(0, 0, image=tk_image, anchor="nw")
            canvas.config(scrollregion=canvas.bbox("all"))

    root = tk.Tk()
    root.title('Stitched Image with Scrollbars')

    # Convert the OpenCV image to PIL format and then to Tkinter format
    original_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    tk_image = ImageTk.PhotoImage(original_image)

    # Create a canvas and add scrollbars
    canvas = tk.Canvas(root, borderwidth=0, highlightthickness=0)
    vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
    hsb = tk.Scrollbar(root, orient="horizontal", command=canvas.xview)
    canvas.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)

    # Function to update the vertical scrollbar when the mouse wheel is used
    def on_vertical_mousewheel(event):
        canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")

    # Function to update the horizontal scrollbar when the shift key and mouse wheel are used
    def on_horizontal_mousewheel(event):
        canvas.xview_scroll(int(-1 * (event.delta / 120)), "units")

    # Creating an instance of ImageZoomer
    zoomer = ImageZoomer(original_image)

    # Binding events to the canvas
    canvas.bind("<MouseWheel>", on_vertical_mousewheel)
    canvas.bind("<Shift-MouseWheel>", on_horizontal_mousewheel)
    canvas.bind("<Control-MouseWheel>", zoomer.zoom)

    vsb.pack(side="right", fill="y")
    hsb.pack(side="bottom", fill="x")
    canvas.pack(side="left", fill="both", expand=True)
    canvas.create_image(0, 0, image=tk_image, anchor="nw")

    # Set the initial scroll region
    canvas.config(scrollregion=canvas.bbox("all"))
    root.mainloop()


def show_test():
    # Example usage
    try:
        zoom_level = 14
        stitched_image, lt_rb = stitch_tiles("D:\\project23\\nautical_chart\\yima_weihai", 37.5838440, 122.0020346,
                                             37.3934620, 122.6021947, zoom_level, border_thickness=0)
        color_1 = np.array([219, 235, 182])
        color_2 = np.array([233, 224, 167])
        color_3 = np.array([255, 218, 170])
        color_list = [color_1, color_2, color_3]

        binary_image = binarization_by_color(stitched_image, color_list, 10)
        # display_image_with_scrollbars(binary_image)

        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4))
        opened_image = cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, kernel, iterations=6)
        dilated_image = cv2.dilate(opened_image, kernel, iterations=4)
        # display_image_with_scrollbars(dilated_image)

        enu_rb = tfb_lla2enu((lt_rb[0], lt_rb[1], 0), (lt_rb[2], lt_rb[3], 0))
        width = abs(enu_rb[0])
        heigh = abs(enu_rb[1])
        pix_size = 5
        new_img_width = int(width / pix_size)
        new_img_height = int(heigh / pix_size)
        # 将图像缩放为指定大小
        resized_image = cv2.resize(dilated_image, (new_img_width, new_img_height), interpolation=cv2.INTER_AREA)
        # display_image_with_scrollbars(resized_image)
        # 将resized_image转换为栅格地图，使用0表示通行，1表示障碍物
        resized_image[resized_image == 0] = 1
        resized_image[resized_image == 255] = 0

        overlay_image = overlay_binary_on_original(stitched_image, dilated_image)
        display_image_with_scrollbars(overlay_image)
    except ValueError as e:
        print(f"Error: {e}")


if __name__ == '__main__':
    show_test()
